$(function () {


    var type = typeInModel;
    var courseId = courseIdInModel;
    var number = numberInModel;
    var jsonData;
    //进入页面后同步发送ajax 获取json 数据
    $.ajax({
        type: 'GET',
        dataType: "json",
        data: {courId:courseId,number:number},
        async: false,
        url: '/temprorary/moni',
        success: function (msg) {
            if (msg) {
                jsonData = msg;
            }
        }
    });


    var userData = jsonData.user;//用户
    var tempSubject = jsonData.tempSubject;//考题
    var testMsg = jsonData.testMsg;//考试科目，题型
    var currentIndex = 0;//当前题目索引
    var countSubject = tempSubject.length;// 题量
    var $subjectIndexSpans;// 右侧所有索引(题号) span元素
    var countTrue = 0;
    var countError = 0;
    var countNotAnswer = 0;
    var countFristTrue = 0;


    //显示身份证号码

    /*  左侧显示考生基础信息 */
    var $spans = $("div.exam1-2 ul>li").find("span");
    countTime();// 显示倒计时

    $spans.eq(0).html(userData.username);//名字
    $spans.eq(1).html("90分钟");
    $spans.eq(2).html(countSubject);//题量
    $spans.eq(3).html(testMsg.carName);//车型
    $spans.eq(4).html(testMsg.courseName);//科目

    $(".exam1-1 span").html(userData.id);//用户id
    $("span#name").html(userData.username);//用户名
    $("span#time").html(formatDateTime(userData.timelimit));//到期时间


    //取消富文本编辑框 html 代码转义
    $.each(tempSubject, function (k, subject) {
        subject.subjectVo.htmltitle = escape2Html(subject.subjectVo.htmltitle);
        subject.subjectVo.htmla = escape2Html(subject.subjectVo.htmla);
        subject.subjectVo.htmlb = escape2Html(subject.subjectVo.htmlb);
        subject.subjectVo.htmlc = escape2Html(subject.subjectVo.htmlc);
        subject.subjectVo.htmld = escape2Html(subject.subjectVo.htmld);
        subject.subjectVo.zhtmltitle = escape2Html(subject.subjectVo.zhtmltitle);
        subject.subjectVo.zhtmla = escape2Html(subject.subjectVo.zhtmla);
        subject.subjectVo.zhtmlb = escape2Html(subject.subjectVo.zhtmlb);
        subject.subjectVo.zhtmlc = escape2Html(subject.subjectVo.zhtmlc);
        subject.subjectVo.zhtmld = escape2Html(subject.subjectVo.zhtmld);
    });

    /* 初始化、显式右侧题目索引*/
    $.each(tempSubject, function (k, subject) {
        $("<span>").html(k + 1).addClass("exam-i").attr("id", subject.ssid).data("value", subject).data("index", k).appendTo("#StrNum");
    });
    //获取右侧所有题号索引的span
    $subjectIndexSpans = $("#StrNum > span");
    //添加点击事件:选择题目
    $subjectIndexSpans.click(function () {
        //点击其他题，技巧描述关闭
       // $(".exam-skill").css("display", "none");
        checkSubject($(this).data("index"));
    });
    //显示抽题数量
    $("#PractRe li span").eq(0).html(countSubject);
    //开始选择第1题
    checkSubject(0);

    //给左下角按钮添加点击事件
    $(".exam1-4 li:eq(0)").click(function (e) {
        $(this).toggleClass("isOpen");
        $(".exam-answer").css("display",($(this).hasClass("isOpen")?"block":"none"));
    });

    $(".exam1-4 li:eq(1)").click(function (e) {
        $(this).toggleClass("isOpen");
    });
    $(".exam1-4 li:eq(2)").click(function (e) {
        $(this).toggleClass("isOpen");
    });

    //选择答案变颜色
    $(".exam-select").delegate(".an-btn", "click", function (e) {
        $(this).toggleClass("isOpen");
    });

    $("#btnPre").click(function () {
        preSubject();
    });
    $("#btnNext").click(function () {
        nextSubject();
    });

    //跳转到下一题
    function nextSubject() {
        //点击其他题
        if (currentIndex < countSubject - 1) {
            currentIndex++;
            checkSubject(currentIndex);
        }
    }

    //跳转到上一题
    function preSubject() {
        //点击其他题
        if (currentIndex > 0) {
            currentIndex--;
            checkSubject(currentIndex);
        }
    }

    //交卷按钮
    $(".exam3-2").delegate("#btnJiaoJuan", "click", function (e) {
        layer.confirm('请确定是否要交卷',
            function (index) {
                layer.open({
                    type: 2,
                    title: '测试结果',
                    area: ['900px', '674px'],
                    fixed: false, //不固定
                    maxmin: true,
                    content: "/p/user/testpage/test_result",
                    success: function (layero, index) {
                        //console.info(testMsg);
                        /*var body = layer.getChildFrame('body', index);
                        body.find("input[name='username']").val(username);*/
                    }
                });
                layer.close(index);
            },
            function () {
                layer.msg('取消操作成功', {icon: 1, time: 1000});
            });
    });

    //错题重做
    $(".exam3-2").delegate("#ErrorId", "click", function (e) {
        layer.confirm('即将进入错题重做，请确认',
            function (index) {
            //点击成功返回错题考试界面
                var torders=[];
                $.each(tempSubject, function (k, subject) {
                    if(subject.status==2){
                        torders.push(subject.torder);
                    }
                });

                if(torders.length<=0){
                    layer.msg('您还没有错题', {icon: 1,time:1000});
                }else{
                    $.ajax({
                        contentType: 'application/json;charset=UTF-8',
                        type: 'PUT',
                        dataType: "json",
                        data: JSON.stringify(torders),
                        url: '/temprorary/test/continue',
                        success: function (result) {
                            // jsonData = result;
                            if(result["status"]!="fail"){
                                window.location.href = "/toTemprorary/1-5-test.html";
                            }

                        }
                    });
                }
                layer.close(index);
        });
    });


    //点击语音读题按钮
    $(".exam2-1").delegate(".laba", "click", function (e) {
        var music = $subjectIndexSpans.eq(currentIndex).data("value").subjectVo.dmusicpath;
        playAudio(music);
    });

    //点击技巧讲解按钮
    $(".exam-jj").delegate("#btnJiqiao", "click", function (e) {
        //闪烁技巧关键字
        showJiqiao();
        //播放技巧语音
        playJiQiaoAudio();
        showJiQiaoImage();
    });
    //显示技巧图片或视频
    function showJiQiaoImage() {
        var $subjectSpan = $subjectIndexSpans.eq(currentIndex);
        var subject = $subjectSpan.data("value");
        if(subject.subjectVo.tmpath){
            $(".exam2-3").html("");
            if(subject.subjectVo.tmtype == 1){
                $(".exam2-3").append( $("<video>").attr("autoplay","autoplay").attr("loop","loop").attr("width","500").attr("autobuffer","").append(($("<source>").attr("type","video/mp4").attr("codecs","avc1.42E01E,mp4a.40.2").attr("src",subject.subjectVo.tmpath))));
            }else{
                $(".exam2-3").append($("<img>").attr("src",subject.subjectVo.tmpath));
            }
        }
    }

    // 播放语音
    function playAudio(path) {
        var $audioSpeak = $("#audioSpeak");
        if (path && !(path === $audioSpeak.attr("src"))) {
            $audioSpeak.get(0).pause();
            $audioSpeak.attr("src", path);
        }
        $audioSpeak.get(0).play();
    }

    // 停止播放语音
    function stopAudio() {
        var $audioSpeak = $("#audioSpeak");
        if ($audioSpeak.attr("src")) {
            $audioSpeak.get(0).pause();
        }
    }


    // 播放技巧语音
    function playJiQiaoAudio() {
        var music = $subjectIndexSpans.eq(currentIndex).data("value").subjectVo.musicpath;
        playAudio(music);
    }


    //答题操作
    $(".exam-select").delegate(".answerBtn", "click", function (e) {
        var $subjectSpan = $subjectIndexSpans.eq(currentIndex);
        var subject = $subjectSpan.data("value");
        var chooseValue = $(this).data("an-value");
        var chooseText = $(this).html();
        //多选题特殊处理
        if (chooseValue == 0) {
            chooseText = "";
            $checked = $(".exam-select").find("a.isOpen");
            if($checked.size()<=1){
                layer.msg('请选择两个以上答案', {icon: 1,time:1000});
                return;
            }
            $checked.each(function () {
                chooseValue = chooseValue + $(this).data("an-value");
                chooseText = chooseText + $(this).html();
            });
        }
        //删除选项按钮，显示所选答案
        $(".exam-select").html("").append(( $("<div>您的答案: </div>").addClass("exam-answe").append($("<span>").html(chooseText).addClass("myanswer"))));
        //判断题目是否正确
        var isTrue = ( chooseValue == subject.subjectVo.answer);
        subject.frist = subject.frist || (isTrue ? 1 : 2);//(subject.first==0?(isTrue?1:2):subject.first);
        subject.status = (isTrue ? 1 : 2);
        subject.choose = chooseValue;
        //刷新左上角样式
        showSpansStyle();
        $.ajax({
            type: 'POST',
            dataType: "json",
            data: {
                "frist": subject.frist,
                "status": subject.status,
                "choose": subject.choose,
                "torder": subject.torder,
                "uid": subject.uid,
                "ssid": subject.ssid,
                "_method": "PUT"
            },
            url: '/temprorary',
            success: function (msg) {
                // console.info("OK");
            }
        });
        if (!isTrue) {//添加错题
            $.ajax({
                type: 'POST',
                dataType: "json",
                data: {"uid": subject.uid, "ssid": subject.ssid},
                url: '/error',
                success: function (msg) {
                    // console.info("添加错题！！！");
                }
            });
        }

        //答对自动翻页
        if (isTrue && $("#btnTrueAutoNext").hasClass("isOpen")) {
            nextSubject();
        }
        //答错必须显示技巧,判断开关是否播放技巧语音
        if (!isTrue) {
            //显示技巧信息
            showJiqiao();
            //播放技巧语音
            if ($("#btnErrAutoVoice").hasClass("isOpen")) {
                var music = $subjectIndexSpans.eq(currentIndex).data("value").subjectVo.musicpath;
                playAudio(music);
            }
        }

        //alert(subject);
    });

// 显示、更新右上角 spans 样式
    function showSpansStyle() {
        var container = $('.exam3-1');
        var scrollTo = $subjectIndexSpans.eq(currentIndex);
        container.scrollTop(
            scrollTo.offset().top - container.offset().top + container.scrollTop()-83
        );
        container.animate({
            scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()-83
        });
        //初始化题目的答题当前状态:0 未答题  1 第一次答对  2 第一次答错,di第二次
        $subjectIndexSpans.each(function (i) {
            var subject = $(this).data("value");
            $(this).html((i+1)+ "<br/>"+(subject.choose?GetSubjectAnswer(subject.choose, subject.subjectVo.type):""));
            if (subject.frist == 0) {
                subject["showClass"] = "exam-not";//未答题
            } else if (subject.frist == 1) {
                subject["showClass"] = "exam-ok";//第一次答题正确 .addClass("exam-ok");
            } else if (subject.frist == 2) {
                if (subject.status == 1) {
                    subject["showClass"] = "exam-ok2";//第一次答错，修改后正确  .addClass("exam-ok2")
                } else if (subject.status == 2) {
                    subject["showClass"] = "exam-error";//第一次答错，未修改或修改也错误 .addClass("exam-error")
                }
            }
            if ($(this).hasClass("exam-ok")) {
                $(this).removeClass("exam-ok");
            }
            if ($(this).hasClass("exam-ok2")) {
                $(this).removeClass("exam-ok2");
            }
            if ($(this).hasClass("exam-error")) {
                $(this).removeClass("exam-error");
            }
            $(this).addClass(subject["showClass"]);
        });
        updateCount();
    }

    //显示、更新统计数据:答对题目 答错题目 未答题目 首正率


    function updateCount() {
        countTrue = 0;
        countError = 0;
        countNotAnswer = 0;
        countFristTrue = 0;

        $subjectIndexSpans.each(function (i) {
            var subject = $(this).data("value");
            // console.info(subject.frist);
            if (subject.status == 1) {
                countTrue++;
            }
            if (subject.status == 2) {
                countError++;
            }
            if (subject.frist == 0) {
                countNotAnswer++;
            }
            if (subject.frist == 1) {
                //alert("AAA");
                countFristTrue++;
            }
        });

        $("#PractRe li:eq(0) span").html("" + countSubject);
        $("#PractRe li:eq(1) span").html("" + countTrue);
        $("#PractRe li:eq(2) span").html("" + countError);
        $("#PractRe li:eq(3) span").html("" + countNotAnswer);
        $("#PractRe li:eq(4) span").html(Math.ceil((countFristTrue / countSubject) * 1000) / 1000.0);

    }

    //==================================================================
    function checkSubject(i) {
        stopAudio();//停止所有语音
        closeJiqiao();//停止技巧
        currentIndex = i;
        showSpansStyle();
        // 1 修改右侧 span 当前索引样式
        $("#StrNum span").removeClass("text-red");
        $("#StrNum span").eq(i).addClass("text-red");
        //2 判断是否显示 上一题 下一题 按钮
        $("#btnPre").css("visibility", "visible");
        $("#btnNext").css("visibility", "visible");
        if (currentIndex == 0) {
            $("#btnPre").css("visibility", "hidden");
        }
        if (currentIndex == countSubject - 1) {
            $("#btnNext").css("visibility", "hidden");
        }
        /* 4 展示题目相关信息  -----------------  开始 */

        var subject = tempSubject[i];
        $(".exam2-1").find(".exam-info").html("" + subject.subjectVo.secondSubName + "题目ID：" + subject.subjectVo.id + "");
        //显示题干
        var subjectType = subject.subjectVo.type;
        $(".exam-title .TiLeiXing").html("(" + ((subjectType == 0 ? "单选题" : (subjectType == 1 ? "判断题" : "多选题"))) + ") : " + ((i + 1) + " 、"));
        $(".exam-title .DaAnText").html(subject.subjectVo.problem);
        $(".exam-title .DaAnHtml").html(subject.subjectVo.htmltitle);
        $(".exam2-1").find("img").remove();
        $(".exam2-1").find("input").remove();
        //显示正确答案
        $(".myanswer:eq(0)").html(GetSubjectAnswer(subject.subjectVo.answer, subjectType));
        $(".exam-answer").css("display",($(".exam1-4 li:eq(0)").hasClass("isOpen")?"block":"none"));
        //显示选项
        $(".exam-text").html("");
        if (subjectType == 0 || subjectType == 2) {//单选题  多选
            if (subject.subjectVo.optiona) {
                $("#timudaanmuban").clone().appendTo(".exam-text").show().find("span:eq(0)").html("A:").end().find("span:eq(1)").html(subject.subjectVo.optiona).end().find("span:eq(2)").html(subject.subjectVo.htmla);
            }
            if (subject.subjectVo.optionb) {
                $("#timudaanmuban").clone().appendTo(".exam-text").show().find("span:eq(0)").html("B:").end().find("span:eq(1)").html(subject.subjectVo.optionb).end().find("span:eq(2)").html(subject.subjectVo.htmlb);
            }
            if (subject.subjectVo.optionc) {
                $("#timudaanmuban").clone().appendTo(".exam-text").show().find("span:eq(0)").html("C:").end().find("span:eq(1)").html(subject.subjectVo.optionc).end().find("span:eq(2)").html(subject.subjectVo.htmlc);
            }
            if (subject.subjectVo.optiond) {
                $("#timudaanmuban").clone().appendTo(".exam-text").show().find("span:eq(0)").html("D:").end().find("span:eq(1)").html(subject.subjectVo.optiond).end().find("span:eq(2)").html(subject.subjectVo.htmld);
            }

        } else if (subjectType == 1) {//判断题
            $("#timudaanmuban").clone().appendTo(".exam-text").show().find("span:eq(1)").html("√").end().find("span:eq(2)").html("√");
            $("#timudaanmuban").clone().appendTo(".exam-text").show().find("span:eq(1)").html("×").end().find("span:eq(2)").html("×");
        }
        //显示答题按钮 即: [A][B][C][D] 或 √ ×
        $(".exam-select").html("");
        if (subjectType == 0) {//单选题
            $("<a>").addClass("an-btn").addClass("A").addClass("answerBtn").html("A").data("an-value", 1).appendTo(".exam-select");
            $("<a>").addClass("an-btn").addClass("B").addClass("answerBtn").html("B").data("an-value", 2).appendTo(".exam-select");
            $("<a>").addClass("an-btn").addClass("C").addClass("answerBtn").html("C").data("an-value", 4).appendTo(".exam-select");
            $("<a>").addClass("an-btn").addClass("D").addClass("answerBtn").html("D").data("an-value", 8).appendTo(".exam-select");
        } else if (subjectType == 2) {//多选
            $("<a>").addClass("an-btn").addClass("A").html("A").data("an-value", 1).appendTo(".exam-select");
            $("<a>").addClass("an-btn").addClass("B").html("B").data("an-value", 2).appendTo(".exam-select");
            $("<a>").addClass("an-btn").addClass("C").html("C").data("an-value", 4).appendTo(".exam-select");
            $("<a>").addClass("an-btn").addClass("D").html("D").data("an-value", 8).appendTo(".exam-select");
            $("<button>").addClass("submitans").addClass("cs-button").addClass("answerBtn").data("an-value", 0).html("确定").data("ssid", subject.subjectVo.secondSubId).appendTo(".exam-select");
        } else if (subjectType == 1) {//判断题
            $("<a>").addClass("an-btn").addClass("answerBtn").html("√").width(40).data("an-value", 1).appendTo(".exam-select");
            $("<a>").addClass("an-btn").addClass("answerBtn").html("×").width(40).data("an-value", 2).appendTo(".exam-select");
        }
        //如果原来是错题，删除选项显示答案

        if(subject.frist!=0){
            //删除选项按钮，显示所选答案
            $(".exam-select").html("").append(( $("<div>您的答案: </div>").addClass("exam-answe").append($("<span>").html(GetSubjectAnswer(subject.choose, subject.subjectVo.type)).addClass("myanswer"))));
        }

        //读题语音判断
        $(".exam2-1").find(".exam-title").append($("<img>").addClass("laba").attr("src", "/static/img/laba.png").css("cursor", "pointer").css("margin-left","15px"));
        /*    媒体类型展示  */
        $(".exam2-3").html("");
        if (subject.subjectVo.mtype == 1) {//视频
            $(".exam2-3").append( $("<video>").attr("autoplay","autoplay").attr("loop","loop").attr("width","500").attr("autobuffer","").append(($("<source>").attr("type","video/mp4").attr("codecs","avc1.42E01E,mp4a.40.2").attr("src",subject.subjectVo.mpath))));
        } else if (subject.subjectVo.mtype == 0) {//图片
            $(".exam2-3").append($("<img>").attr("src",subject.subjectVo.mpath));
        } else if (subject.subjectVo.mtype == 2) {//媒体类型  2：无
            $(".exam2-3").html("");
        }
        /*  展示题目相关信息  -----------------  结束 */

        /* 技巧描述显示 */
        if (subject.subjectVo.explain) {//有技巧描述
            $(".exam-describe").html(subject.subjectVo.explain);
        } else {
            $(".exam-describe").html("");
        }
    }



    //页首几个按钮点击时间
    $("#btnBackIndex").click(function () {
        window.location.href="/p/user/user-index";
    });
    $("#btnBackPre").click(function () {
        window.location.href="/p/user/user-index?carId="+testMsg.carId+"&exerId="+testMsg.exerId+"&couserId="+testMsg.courseId;
    });

    $("#btnBackMyErr").click(function () {
      //  window.location.href = "/toTemprorary/1-3-test.html";
        ( function() {
                layer.open({
                    type: 2,
                    title: '我的错题',
                    area: ['350px', '230px'],
                    fixed: false,
                    maxmin: true,
                    shadeClose: true,
                    content: "/page/user/errorSub4Eaxm.jsp",
                    success: function (layero, index) {
                    }
                });
            }
        )();
    });
    $("#btnExitExam").click(function () {
        window.location.href = "/user/loginOut?type=1";
    });

});

